package team.pra.manager.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import team.pra.manager.pojo.User;
import team.pra.manager.service.ShiroService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author csw
 * 该控制器用于用户登录后台的相关操作
 */
@RestController
public class LoginController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ShiroService shiroService;

    @PostMapping(value = "/user/login")
    public Map<String, Object> login(@Validated User login, BindingResult bindingResult) {
        logger.info("{}--{}",login.getUsername(),login.getPassword());
        Map<String, Object> result = new HashMap<>();
        if (bindingResult.hasErrors()) {
            result.put("status", 400);
            result.put("msg", bindingResult.getFieldError().getDefaultMessage());
            return result;
        }

        String username = login.getUsername();
        String password = login.getPassword();

        //用户信息
        User user = shiroService.findByUsername(username);
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(password)) {
            result.put("status", 400);
            result.put("msg", "账号或密码有误");
        } else {
            //生成token，并保存到数据库
            result = shiroService.createToken(user.getId());
            result.put("status", 200);
            result.put("msg", "登录成功");
        }
        return result;
    }
    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public Map<String, Object> logout(@RequestParam("token")String token) {
        Map<String, Object> result = new HashMap<>();
        shiroService.logout(token);
        result.put("status", 200);
        result.put("msg", "您已退出系统");
        return result;
    }

}
